package per.jdz.demo.controller;

import com.mybatisflex.core.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import per.jdz.demo.domain.entity.CrawlerDataRecord;
import per.jdz.demo.domain.vo.reponse.ApiResult;
import per.jdz.demo.domain.vo.request.CrawlerCountReq;
import per.jdz.demo.service.CrawlerDataRecordService;
import per.jdz.demo.utils.DateUtil;

import javax.annotation.Resource;

import static per.jdz.demo.domain.entity.table.CrawlerDataRecordTableDef.CRAWLER_DATA_RECORD;

@RestController
@Slf4j
@RequestMapping("/crawler")
// TODO 接口校验
public class CrawlerDataRecordController {
    @Resource
    private CrawlerDataRecordService crawlerDataRecordService;

    @PostMapping("/getTransactionDataCount")
    public ApiResult getTransactionDataCount(@RequestBody CrawlerCountReq req) {
        QueryWrapper query = QueryWrapper.create()
                .select(CRAWLER_DATA_RECORD.CRAWLER_TOTAL)
                .where(CRAWLER_DATA_RECORD.CITY.eq(req.getCity()).and(CRAWLER_DATA_RECORD.TRANSACTION_TIME.isNotNull()).and(CRAWLER_DATA_RECORD.CRAWLER_TYPE.eq(req.getCrawlerType())))
                .orderBy(CRAWLER_DATA_RECORD.CREATE_TIME.desc())
                .limit(1);
        Integer total = crawlerDataRecordService.getObjAsOpt(query, Integer.class).orElse(0);
        return ApiResult.success(total);
    }

    @PostMapping("/getOtherDataCount")
    public ApiResult getOtherDataCount(@RequestBody CrawlerCountReq req) {
        QueryWrapper query = QueryWrapper.create()
                .select(CRAWLER_DATA_RECORD.CRAWLER_TOTAL)
                .where(CRAWLER_DATA_RECORD.CITY.eq(req.getCity()).and(CRAWLER_DATA_RECORD.OTHER_TIME.isNotNull()).and(CRAWLER_DATA_RECORD.CRAWLER_TYPE.eq(req.getCrawlerType())))
                .orderBy(CRAWLER_DATA_RECORD.CREATE_TIME.desc())
                .limit(1);
        Integer total = crawlerDataRecordService.getObjAsOpt(query, Integer.class).orElse(0);
        return ApiResult.success(total);
    }

    @PostMapping("/addCrawlerRecord")
    public ApiResult addCrawlerRecord(@RequestBody CrawlerDataRecord crawlerDataRecord) {
        crawlerDataRecordService.save(crawlerDataRecord);
        return ApiResult.success();
    }
}